﻿using System;
using System.Web.Mvc;
using Southern.Common.Utilities;
using Southern.Controllers;
using Southern.Models.Southern;
using Southern.Models.Southern.Base;
using Southern.Models.Southern.Partials;

namespace Southern.Areas.Admin.Controllers
{
    public class UserController : AdminBaseController
    {
        public ActionResult Index()
        {
            var users = Services.Get<IUserRepository>().GetUsers();
            return View(users);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(SysUser sysUser)
        {
            sysUser.CreatedDate = DateTime.Now;
            sysUser.Password = SecurityUtility.MD5Encrypt(sysUser.Password);
            var isSuccess = Services.Get<IUserRepository>().CreateUser(sysUser);
            if (isSuccess)
            {
                return RedirectToAction("Index", "User", new { area = "Admin" });
            }
            return View(sysUser);
        }

        public ActionResult Edit(int id)
        {
            if (id > 0)
            {
                SysUser sysUser = Services.Get<IUserRepository>().GetUser(id);
                return View(sysUser);
            }
            else
            {
                return HttpNotFound();
            }
            return View();
        }

        [HttpPost]
        public ActionResult Edit(SysUser sysUser)
        {
            sysUser.CreatedDate = DateTime.Now;
            var isSuccess = Services.Get<IUserRepository>().UpdateUser(sysUser);
            if (isSuccess)
            {
                return RedirectToAction("Index", "User", new { area = "Admin" });
            }
            return View(sysUser);
        }

        public ActionResult Delete(int id)
        {
            
            return View();
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            if (id > 0)
            {
                int isDelete = Services.Get<IUserRepository>().DeleteUser(id);
                if (isDelete > 0)
                {
                    return RedirectToAction("Index", "User", new { area = "Admin" });
                }
            }
            else
            {
                return HttpNotFound();
            }
            return RedirectToAction("Index", "User", new { area = "Admin" });
        }
    }
}
